<template>
  <video :id="options.pid" playsinline webkit-playsinline>
  </video>
</template>
<script>
function loadTcScript (cb) {
  loadScript(cb, {
    id: 'tcPlayerScriptId',
    url: 'https://web.sdk.qcloud.com/player/tcplayer/release/v4.6.0/tcplayer.v4.6.0.min.js'
  })
}
function loadScript (cb, obj) {
  if (document.getElementById(obj.id)) {
    cb()
  } else {
    const script = document.createElement('script')
    script.async = true
    script.src = obj.url
    script.id = obj.id
    script.onload = () => {
      cb()
    }
    document.body.appendChild(script)
  }
}
export default {
  name: 'VideoPlayer',
  props: {
    width: {
      type: Number,
      required: false,
      default: 720
    },
    height: {
      type: Number,
      required: false,
      default: 500
    },
    options: {
      type: Object,
      required: true
    }
  },
  mounted () {
    this.initVideo()
  },
  methods: {
    loadJS () {
      if (window.TCPlayer) {
        this.initVideo()
      } else {
        loadTcScript(() => {
          this.initVideo()
        })
      }
    },
    initVideo () {
      const playerParm = {
        fileID: this.options.fileID,
        appID: '1306498106',
        psign: this.options.psign,
        plugins: {
          ProgressMarker: true,
          ContextMenu: {
            levelSwitch: {
              open: true,
              switchingText: '开始切换清晰度 ',
              switchedText: '切换成功',
              switchErrorText: '切换失败'
            }
          },
          ContinuePlay: { // 开启续播功能
            auto: true,
            text: '上次播放至 ',
            btnText: '恢复播放'
          },
          DynamicWatermark: {
            speed: 0.2,
            content: this.options.waterMark
          }
        },
        autoplay: true,
        language: 'zh-CN',
        height: this.height,
        width: this.width
      }
      console.log(playerParm)
      setTimeout(() => {
        if (!this.player) {
          this.player = window.TCPlayer(this.tcPlayerId, playerParm)
        } else {
          this.player.loadVideoByID(playerParm)
        }
      })
    }
  },
  watch: {
    options: {
      handler (newV, oldV) {
        this.$nextTick(() => {
          this.loadJS()
        })
      },
      immediate: true,
      deep: true
    }
  }
}
</script>